from captcha.image import ImageCaptcha
from random import randint
from io import BytesIO

def generate_captcha_image():
    """
    生成图片验证码
    :return: chars 验证码的值， buf.getvalue() 验证码的Bytes值
    """

    list = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
            'v', 'w', 'x', 'y', 'z',
            '', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
            'W', 'X', 'Y', 'Z']
    chars = ''
    for i in range(4):
        chars += list[randint(0, 62)]
    image = ImageCaptcha().generate_image(chars)

    # print(f"图片验证码 = {chars}")

    # image.show()
    # 内存文件操作
    buf = BytesIO()
    # 将图片保存在内存中，文件类型为png
    image.save(buf, 'png')

    # 打印图片保存在内存的Bytes字节
    # print(buf.getvalue())

    return chars, buf.getvalue()


